package com.chookss.video.recommend;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.VideoEvent;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.CircleImageView;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class VideoDetailVideoFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener{

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    ConsecutiveScrollerLayout llBg;

    private MyVideoDetailAdapter adapter;
    private List<VideoEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private String courseCode;
    private String playVideoId;
    private int source=0;
    private String effTime,invalidTime;//学习任务所用时间
    public VideoDetailVideoFragment(String courseCode,String videoId,int source,String effTime,String invalidTime) {
        this.courseCode = courseCode;
        this.playVideoId = videoId;
        this.source = source;
        this.effTime = effTime;
        this.invalidTime = invalidTime;
    }

    public VideoDetailVideoFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.common_recyclerview_top, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        llBg.setBackgroundColor(Color.parseColor("#ffffff"));
        ivNone.setBackgroundResource(R.drawable.icon_default_no_video);
        rv.setPadding(Utils.dip2px(mContext, 12), 0, Utils.dip2px(mContext, 12), 0);
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rv.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        adapter = new MyVideoDetailAdapter(R.layout.item_videodetail_video, mContext, list);
        rv.setAdapter(adapter);
        getData();
    }
    private RefreshLayout refreshLayout;

    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }
    private void getData() {
        Map<String, String> map = new HashMap<>();
        String url="";
        if(source==2){
            map.put("courseCode", courseCode);
            map.put("effTime", effTime);
            map.put("invalidTime", invalidTime);
            url= Urls.selectTaskByCourseCode;
        }else{
            map.put("courseCode", courseCode);
            url= Urls.selectCourseConnectVideo;
        }

        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequestCompat(null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {

                JSONObject jsonObject = JSONObject.parseObject(data);
                if ("200".equals(jsonObject.getString("code"))) {
                    loadEnd();
                    if(rv==null||llNone==null){
                        return;
                    }
                    String total=jsonObject.getString("total");
                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                    List<VideoEntity> VideoEntitys=new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject userJson =jsonArray.getJSONObject(i);
                        VideoEntity videoEntity = JSON.toJavaObject(userJson,VideoEntity.class);
                        VideoEntitys.add(videoEntity);
                    }
                    if (currentPage == 1) {
                        list.clear();
                        adapter.notifyDataSetChanged();
                    }
                    int oldIndex=list.size();
                    HashMap<String,String> map=new HashMap<>();
                    map.put("videoNum",total);
                    EventBus.getDefault().post(new MyEvent(map));
                    if (VideoEntitys != null && VideoEntitys.size() > 0) {
                        if(VideoEntitys.size()<pageSize){
                            isEnd = true;
                        }
                        list.addAll(VideoEntitys);
                        adapter.notifyItemRangeChanged(oldIndex,VideoEntitys.size());
                        rv.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    } else {
                        isEnd = true;
                        if (list.size() == 0) {
                            rv.setVisibility(View.GONE);
                            llNone.setVisibility(View.VISIBLE);
                        }
                    }
                    loadEnd();

                }else{
                    loadEnd();
                }

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
//        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<VideoEntity>>>() {
//        }.getType(), null, Urls.selectCourseConnectVideo, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<VideoEntity>>() {
//            @Override
//            public void onSuccess(List<VideoEntity> data) {
//                if (currentPage == 1) {
//                    list.clear();
//                }
//                if (data != null && data.size() > 0) {
//                    if(data.size()<pageSize){
//                        isEnd = true;
//                    }
//                    list.addAll(data);
//                    adapter.notifyDataSetChanged();
//                    rv.setVisibility(View.VISIBLE);
//                    llNone.setVisibility(View.GONE);
//                    HashMap<String,String> map=new HashMap<>();
//                    map.put("videoNum",list.size()+"");
//                    EventBus.getDefault().post(new MyEvent(map));
//                } else {
//                    isEnd = true;
//                    if (list.size() == 0) {
//                        rv.setVisibility(View.GONE);
//                        llNone.setVisibility(View.VISIBLE);
//                    }
//                }
//                loadEnd();
//            }
//
//            @Override
//            public void onError(String errorMsg) {
//                loadEnd();
//                MyToast.show(Utils.onErrorTips(errorMsg));
//            }
//        });
    }

    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if(map.containsKey("videoId")){
                for (int i = 0; i < list.size(); i++) {
                    if(list.get(i).videoId.equals(map.get("videoId"))){
                        if(map.containsKey("videoCollectCounts")){
                            list.get(i).videoCollectCounts=map.get("videoCollectCounts");
                        }
                        if(map.containsKey("videoLikeCounts")){
                            list.get(i).videoLikeCounts=map.get("videoLikeCounts");
                        }
                        if(map.containsKey("isCollect")){
                            list.get(i).isCollect=map.get("isCollect");
                        }
                        if(map.containsKey("isLike")){
                            list.get(i).videoLikeCounts=map.get("isLike");
                        }
                        if(map.containsKey("videoPlayCounts")){
                            list.get(i).videoPlayCounts=map.get("videoPlayCounts");
                            list.get(i).isPlay="1";
                            adapter.notifyItemChanged(i);
                        }
                        if(map.containsKey("compeleteFlag")){
                            list.get(i).compeleteFlag=map.get("compeleteFlag");
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        }
    }

    class MyVideoDetailAdapter extends BaseQuickAdapter<VideoEntity, BaseViewHolderEx> {
        private Context context;

        public MyVideoDetailAdapter(int layoutResId, Context context, @Nullable List<VideoEntity> data) {
            super(layoutResId, data);
            this.context = context;

        }

        @Override
        protected void convert(BaseViewHolderEx helper, VideoEntity item) {
            ImageView ivVideo = helper.getView(R.id.ivVideo);
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvVideoTitle = helper.getView(R.id.tvVideoTitle);
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvPeople = helper.getView(R.id.tvPeople);
            GlideUtils.load(mContext, item.videoCoverPath, ivVideo, R.drawable.default_vedio);
            GlideUtils.loadAvatar(mContext,  item.headPhotoThumbUrl, ivHead);
            tvVideoTitle.setText(item.videoTitle );
            tvName.setText(item.employeeName);
            tvPeople.setText(Utils.changeCounts(item.videoPlayCounts) + "人看过");
            if(item.videoId.equals(playVideoId)){
                tvType.setVisibility(View.VISIBLE);
                tvType.setText("正在播放");
                tvType.setBackgroundResource(R.drawable.shape_main_color);
                tvVideoTitle.setTextColor(mContext.getResources().getColor(R.color.main_color));
            }else{
                if("1".equals(item.compeleteFlag)){
                    tvType.setVisibility(View.VISIBLE);
                    tvType.setText("已学完");
                    tvType.setBackgroundResource(R.drawable.shape_00c993);
                    tvVideoTitle.setTextColor(mContext.getResources().getColor(R.color.text_gray3));
                }else{
                    if("1".equals(item.isPlay)) {
                        tvType.setVisibility(View.VISIBLE);
                        tvType.setText("已看过");
                        tvType.setBackgroundResource(R.drawable.shape_00c993);
                        tvVideoTitle.setTextColor(mContext.getResources().getColor(R.color.text_gray3));
                    }else{
                        tvType.setVisibility(View.GONE);
                        tvVideoTitle.setTextColor(mContext.getResources().getColor(R.color.text_gray3));
                    }
                }
            }


            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    playVideoId=item.videoId;
                    adapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new VideoEvent(item));
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

}
